<?php
/**
 *
 * 版权所有：安德玛(underArmour)
 * 作    者：1554324405@qq.com
 * 日    期：2020-05-20
 * 版    本：1.0.0
 * 功能说明：网红任务控制器。
 *
 **/
namespace Admin\Controller;

class TaskController extends ComController
{
    /**
     * 首页
     */
    public function index()
    {
        $p = isset($_GET['p']) ? intval($_GET['p']) : '1';
        $cid = I('cid','','htmlspecialchars');
        $title = I('title','','htmlspecialchars');
        $status = I('status','','htmlspecialchars');
        $pay_status = I('pay_status','','htmlspecialchars');
        $level_id = I('user_level','','htmlspecialchars');
        $field = I('get.field','','htmlspecialchars');
        $sort = I('get.sort','','htmlspecialchars');
        // 获取平分类
        $category = M('category')->order('o asc')->select();
        // 接单会员等级
        $user_level_list = M('user_level')->where(array('is_r'=>1))->order('o asc')->select();
        $model = M();
        $sqlWhere = "1=1 and ";
        if($cid){
            $sqlWhere .= "a.cid=".$cid." and ";
        }
        if($title){
            if($title == '平台'){
                $sqlWhere .= "a.uid=0 and ";
            }else{
                $sqlWhere .= "(a.`title` like '%{$title}%' or a.task_no like '%{$title}%' or c.username like '%{$title}%' or c.nickname like '%{$title}%') and ";
            }
        }
        if($status){
            if($status == 3){
                $sqlWhere .= "date_format(a.end_t,'%Y-%m-%d') < date_format(now(),'%Y-%m-%d') and a.hasdid_num < a.num and ";
            }
            if($status == 2){
                $sqlWhere .= "a.hasdid_num >= a.num and ";
            }
            if($status == 1){
                $sqlWhere .= "a.hasdid_num < a.num and date_format(a.end_t,'%Y-%m-%d') >= date_format(now(),'%Y-%m-%d') and ";
            }
        }
        if($pay_status){
            if($pay_status == -1){
                $sqlWhere .= "a.pay_status = 0 and ";
            }else{
                $sqlWhere .= "a.pay_status = ".$pay_status." and ";
            }
        }
        
        if($level_id){
            $sqlWhere .= "a.user_level = ".$level_id." and ";
        }
        
        $sqlWhere = msubstr($sqlWhere, 0, utf8_strlen($sqlWhere) - 4, "utf-8", false);
        
        $sortSql = "a.on_top desc,a.id desc";
        if($field and $sort){
            $sortSql = "a.".$field." ".$sort;
        }
        
        
        $pagesize = 20;#每页数量
        $offset = $pagesize * ($p - 1);//计算记录偏移量
        $count = $model->query("select count(*) as total,case when date_format(a.end_t,'%Y-%m-%d') < date_format(now(),'%Y-%m-%d') and a.hasdid_num < a.num 
                                then 3 when a.hasdid_num>=a.num then 2 else 1 end as `status` from ".C('DB_PREFIX')."task a left join 
                                ".C('DB_PREFIX')."category b on a.cid=b.id left join ".C('DB_PREFIX')."user c on a.uid=c.id where ".$sqlWhere);
        $count = $count[0]['total'];
        $sql = "select a.*,b.title as category_title,case when date_format(a.end_t,'%Y-%m-%d') < date_format(now(),'%Y-%m-%d') and a.hasdid_num < a.num 
                then 3 when a.hasdid_num>=a.num then 2 else 1 end as `status`,c.username,c.nickname from ".C('DB_PREFIX')."task a left join ".C('DB_PREFIX')."category b 
                on a.cid=b.id left join ".C('DB_PREFIX')."user c on a.uid=c.id where ".$sqlWhere." order by ".$sortSql." limit ".$offset . "," . $pagesize;
        $list = $model->query($sql);
        foreach ($list as $k=>&$v){
            // 允许接单会员等级
            $user_level = $v['user_level'];
            $user_level_arr = explode(',', $user_level);
            $info_title = '';
            foreach ($user_level_arr as $n=>&$m){
                $info = M('user_level')->where('id='.$m)->field('title')->find();
                $info_title .= $info['title']." ";
            }
            $list[$k]['level_info'] = $info_title;
            // 任务要求
            $money_type = $v['money_type'];
            $money_type_arr = explode(',', $money_type);
            $money_info_title = '';
            foreach ($money_type_arr as $h=>&$l){
                $money_info = M('money_type')->where('id='.$l)->field('title')->find();
                $money_info_title .= $money_info['title'].' ';
            }
            $list[$k]['money_info'] = $money_info_title;
            // 发布人
            if($v['uid'] == 0){
                $list[$k]['author'] = '平台';
            }else{
                $user = M('user')->where('id='.$v['uid'])->find();
                $list[$k]['author'] = $user['username'];
            }
        }
        $page = new \Think\Page($count, $pagesize);
        $page = $page->show();
        $this->assign('list', $list);
        $this->assign('p', $p);
        $this->assign('page', $page);
        $this->assign('status', $status);
        $this->assign('cid', $cid);
        $this->assign('category', $category);
        $this->assign('pay_status',$pay_status);
        $this->assign('user_level_list',$user_level_list);
        $this->assign('level_id',$level_id);
        $this->assign('field',$field);
        $this->assign('sort',$sort);
        $this->display();
    }
    
    
    /**
     * 新增
     */
    public function add()
    {
        if(IS_POST)
        {
            //$data['title'] = I('post.title','','htmlspecialchars');
            $data['cid'] = I('post.cid','','htmlspecialchars');
            $data['price'] = I('post.price','','htmlspecialchars');
            $data['num'] = I('post.num','','htmlspecialchars');
            //$data['url'] = I('post.url','','htmlspecialchars');
            $data['pay_status'] = I('post.pay_status',1,'htmlspecialchars');
            $data['end_t'] = I('post.end_t','','htmlspecialchars');
            $data['user_level'] = I('post.user_level','','htmlspecialchars');
            $data['money_type'] = implode(",",I('post.money_type','','htmlspecialchars'));
            $data['amount_price'] = I('post.amount_price','','htmlspecialchars');
            $data['pic'] = I('post.pic','','htmlspecialchars');
            $data['remark'] = I('post.remark','','htmlspecialchars');
            $title_arr = I('post.title');
            $url_arr = I('post.url');
            
            
            if(empty($title_arr) or empty($url_arr) or !$data['cid'] or !$data['price'] or !$data['num']
                or !$data['end_t'] or !$data['user_level'] or !$data['money_type'] or !$data['amount_price']){
                $this->error('表单必填项存在空项，请检查表单输入！');
            }
            
            foreach ($title_arr as $k=>$v){
                $data['title'] = $v;
                $data['url'] = $url_arr[$k];
                $data['task_no'] = getTaskNo();
                $data['t'] = time();
                $data['uid'] = 0;
                M('task')->data($data)->add();
            }
            
            addlog('新增任务成功');
            $this->success('操作成功',U('index'));
//             $data['task_no'] = getTaskNo();
//             $data['t'] = time();
//             $data['uid'] = 0;
//             $res = M('task')->data($data)->add();
//             if($res){
//                 addlog('新增任务，ID：'.$res);
//                 $this->success('操作成功',U('index'));
//             }else{
//                 $this->error('操作失败，请稍后再试！');
//             }
        }
        else
        {
            // 平台分类
            $task_cate = M('category')->order('o asc')->select();
            // 会员等级
            $user_level = M('user_level')->where('is_r=1')->order('o asc')->select();
            // 任务结构
            $money_type = M('money_type')->select();
            $this->assign('money_type',$money_type);
            $this->assign('user_level',$user_level);
            $this->assign('task_cate',$task_cate);
            $this->assign('method',U('Task/add'));
            $this->display('form');
        }
    }
    
    
    /**
     * 修改
     */
    public function update()
    {
        $id = I('id');
        $p = I('p',1);
        $uid = I('uid',0);
        if(!$id){
            $this->error('传参为空！');
        }
        if(IS_POST){
            $data['title'] = I('post.title','','htmlspecialchars');
            $data['cid'] = I('post.cid','','htmlspecialchars');
            $data['price'] = I('post.price','','htmlspecialchars');
            $data['url'] = I('post.url','','htmlspecialchars');
            $data['num'] = I('post.num','','htmlspecialchars');
            $data['end_t'] = I('post.end_t','','htmlspecialchars');
            $data['user_level'] = I('post.user_level','','htmlspecialchars');
            $data['money_type'] = implode(",",I('post.money_type','','htmlspecialchars'));
            $data['amount_price'] = I('post.amount_price','','htmlspecialchars');
            $data['pic'] = I('post.pic','','htmlspecialchars');
            $data['remark'] = I('post.remark','','htmlspecialchars');
            $data['pay_status'] = I('post.pay_status',1,'htmlspecialchars');
            if(!$data['title'] or !$data['cid'] or !$data['price'] or !$data['num'] or !$data['url']
                or !$data['end_t'] or !$data['user_level'] or !$data['money_type'] or !$data['amount_price']){
                    $this->error('表单必填项存在空项，请检查表单输入！');
            }
                
            if(!$this->checkUrl($data['url'])){
                $this->error('任务地址必须以http(s)开头！');
            }
                
            
            $data['update_t'] = time();
            $res = M('task')->data($data)->where('id='.$id)->save();
            if($res){
                addlog('修改任务，ID：'.$id);
                $this->success('操作成功',U('index',array('p'=>$p)));
            }
        }else{
            $vo = M('task')->where('id='.$id)->find();
            // 平台分类
            $task_cate = M('category')->order('o asc')->select();
            // 会员等级
            $user_level = M('user_level')->where('is_r=1')->order('o asc')->select();
            foreach ($user_level as $k=>&$v){
                $arr1 = explode(",", $vo['user_level']);
                if(in_array($v['id'],$arr1)){
                    $user_level[$k]['checked'] = 1;
                }
            }
            // 任务结构
            $money_type = M('money_type')->select();
            foreach ($money_type as $k=>&$v){
                $arr2 = explode(",", $vo['money_type']);
                if(in_array($v['id'],$arr2)){
                    $money_type[$k]['checked'] = 1;
                }
            }
            //凭证
            if(!empty($vo['pz'])){
                $pz = explode(',', $vo['pz']);
                $this->assign('pz',$pz);
            }else{
                $this->assign('pz',[]);
            }
            //图片
            if(!empty($vo['pic'])){
                $pic = explode('|', $vo['pic']);
                $this->assign('pics',$pic);
            }else{
                $this->assign('pics',[]);
            }
            //支付方式
            if($vo['pay_id']){
                $pay_type = M('pay_type')->where('id='.$vo['pay_id'])->find();
                $this->assign('pay_name',$pay_type['name']);
            }
            $this->assign('money_type',$money_type);
            $this->assign('user_level',$user_level);
            $this->assign('task_cate',$task_cate);
            $this->assign('method',U('Task/update'));
            $this->assign('vo',$vo);
            $this->assign('p',$p);
            $this->display('form');
        }
    }
    
    
    /**
     * 删除
     */
    public function delete()
    {
        $ids = isset($_REQUEST['ids']) ? $_REQUEST['ids'] : false;
        $p = isset($_GET['p']) ? intval($_GET['p']) : '1';
        if ($ids) {
            if (is_array($ids)) {
                $ids = implode(',', $ids);
                $map['id'] = array('in', $ids);
                $where['task_id'] = array('in', $ids);
            } else {
                $map = 'id=' . $ids;
                $where = 'task_id=' . $ids;
            }
            if (M('task')->where($map)->delete()) {
                addlog('删除任务，ID：' . $ids);
                M('user_task')->where($where)->delete();
                $this->success('恭喜，删除任务成功！',U('index',array('p'=>$p)));
            } else {
                $this->error('参数错误！');
            }
        } else {
            $this->error('参数错误！');
        }
    }
    
    /**
     * 置顶
     */
    public function ontop()
    {
        $id = I('id');
        $p = I('p');
        $ontop = I('ontop');
        $cid = I('cid');
        $user_level = I('user_level');
        $status = I('status');
        $pay_status = I('pay_status');
        if($ontop == 99){
            $ontop = time();
            $msg = '置顶任务，ID：'.$id;
        }else{
            $msg = '取消任务置顶，ID：'.$id;
        }
        M('task')->data(array('on_top'=>$ontop))->where('id='.$id)->save();
        addlog($msg);
        redirect(U('index',array('p'=>$p,'cid'=>$cid,'user_level'=>$user_level,'status'=>$status,'pay_status'=>$pay_status)));
    }
    
    private function checkUrl($url)
    {
        if(preg_match("/^(http:\/\/|https:\/\/).*$/",$url)){
            return 1;
        }else{
            return 0;
        }
    } 
}